<?php
namespace control;

/*
*证照管理类
*/

class certificateClass extends adIndexClass
{
    private const page = 'certificate';
    private const table = 'certificate';
    private const title = '证照管理';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'      => [
                        'name'  => "证照类别",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "证照名称",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => "证照编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'startDate'         => [
                        'name'  => '发证日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'official'          => [
                        'name'  => '发证机关',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'endDate'          => [
                        'name'  => '有效期至',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'auditDate'          => [
                        'name'  => '下次审核日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'isEnd'          => [
                        'name'  => '到期预警',
                        'width' => 150,
                    ],
                    'remindStid'          => [
                        'name'  => '到期提醒人',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "证照类别" => select(["name" => "type", 'option' => explode('，', para('certType'))]),
                    "证照名称"     => text(array("name" => "name")),
                    "证照编号"     => text(array("name" => "orderNo")),
                ],
                [
                    '到期提醒人'   => selectMultiple(["name" => "staffId", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    "到期预警" => select(["name" => "isEnd", 'option' => ['是', '否']]),
                    '下次审核时间'   => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//证照编号
            "name" => $this->post('name'),//证照名称
        );
        //全等查询数组
        $equal = array(
            "remindStid" => $this->post('staffId'),//到期提醒人
            "type" => $this->post('type'),//证照类别
        );
        $and = "";
        if ($this->post('createTime')) {
            $timeArr = explode('~', $this->post('createTime'));
            $and .= " and auditDate >='{$timeArr[0]}' and auditDate <='{$timeArr[1]}'";
        }
        if ($this->post('isEnd') =='是'){
            $and.=" and DATEDIFF(DATE_FORMAT(now(),'%Y-%m-%d'),auditDate) <= limitDay";
        }elseif($this->post('isEnd') =='否'){
            $and.=" and DATEDIFF(DATE_FORMAT(now(),'%Y-%m-%d'),auditDate) > limitDay";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $_SESSION[self::page]['where'] = $where;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "endDate":
                        $row[] = $array['isLong']?'永久':$array['endDate'];
                        break;
                    case "isEnd":
                        $isEnd = '否';
                        if (strtotime($array['auditDate']) <= strtotime("+{$array['limitDay']} day")) {
                            $isEnd = "<span style='color: red'>是</span>";
                        }
                        $row[] = $isEnd;
                        break;
                    case "remindStid":
                        $row[] = self::findStaff($array['remindStid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id =$this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $checked = $info['isLong']?'checked':'';
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    "<div class='small-title'>基本信息</div>"
                ],
                [
                    must . "证照类别：" => select(["name" => "type", 'option' => explode('，', para('certType')), 'title' => '证照类别', 'value' => $info['type']])
                ],
                [

                    must . "证照名称：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    "证照编号：" => text(["name" => "orderNo", 'class' => 'text', "value" => $info['orderNo']]),
                ],
                [
                    must . "发证日期：" => text(["name" => "startDate", 'laydate' => [], 'class' => 'text', "value" => $info['startDate']]),
                    must . "发证机关：" => text(["name" => "official", 'class' => 'text', "value" => $info['official']]),
                ],
                [
                    must . "有效期至：" => "<div class='flex-box'>".text(["name" => "endDate", 'laydate' => [], 'class' => 'text', "value" => $info['endDate']])."<label class='checkbox width100'><input name='isLong' type='checkbox' $checked value='1'><span></span>&nbsp;永久</label></div>",
                    "下次审核日期：" => text(["name" => "auditDate", 'laydate' => [], 'class' => 'text', "value" => $info['auditDate']]),
                ],
                [
                    "到期提醒人：" => selectMultiple(["name" => "remindStid", "value" => $info['remindStid'], 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '到期提醒人']),
                    "提前提醒天数：" => text(["name" => "limitDay", 'class' => 'text', "value" => $info['limitDay']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
                [
                    "<div class='small-title'>附件</div>" .
                    fileUploadClass::addFileComponent($info['id'], '证照管理', self::page, self::page . 'EditForm')
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 500, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //附件
        $fileIdArr = $this->post('fileId');
        $field = [
            'type' => $this->post('type'),
            'startDate' => $this->post('startDate'),
            'endDate' => $this->post('isLong')?'':$this->post('endDate'),
            'isLong' => $this->post('isLong'),
            'name' => $this->post('name'),
            'orderNo' => $this->post('orderNo'),
            'official' => $this->post('official'),
            'auditDate' => $this->post('auditDate'),
            'remindStid' => $this->post('remindStid'),
            'limitDay' => $this->post('limitDay'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'type' => '证照类型',
            'startDate' => '发证日期',
            'name' => '证照名称',
            'official' => '发证机关',
        ];
        $rules = [
            'type' => 'required',
            'startDate' => 'required',
            'name' => 'required',
            'official' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(empty($field['isLong']) && empty($field['endDate'])){
            $json['warn'] = '请选择有效期至';
        } elseif(empty($field['isLong']) && empty($field['auditDate'])){
            $json['warn'] = '请选择下次审核日期';
        } elseif(!$field['isLong'] && strtotime($field['startDate']) >= strtotime($field['endDate'])){
            $json['warn'] = '有效期不能小于等于发证日期';
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];

            }
            if ($this->power(self::page,'del')){
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            /*******附件****************/
            $fileCollection = fileUploadClass::showFile($info['id'], '证照管理');
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "证照类别" => $info['type'],
                        "证照名称" => $info['name'],
                        "证照编号" => $info['orderNo'],
                        "发证日期" => $info['startDate'],
                    ),
                    array(
                        "发证机关" => $info['official'],
                        "有效期至" => $info['isLong']?'永久':$info['endDate'],
                        "下次审核日期" => $info['auditDate'],
                        "到期提醒人" => self::findStaff($info['remindStid']),
                    ),
                    array(
                        "提前提醒天数" => $info['limitDay'] . '天',
                    ),
                    array(
                        "备注" => $info['text'],
                    ),
                ),
                "附件" => array(
                    array(
                        $fileCollection
                    ),
                ),
                '系统信息' => array(
                    array(
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => self::null($info['updateTime']),
                    ),
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
